import requests,openpyxl

class getZhihu:

    def req(self):

        articles_list = []

        url = 'https://www.zhihu.com/api/v4/members/zhang-jia-wei/articles'

        offset = 0

        while True:
            params = {

                'include':'data[*].comment_count,suggest_edit,is_normal,thumbnail_extra_info,thumbnail,can_comment,comment_permission,admin_closed_comment,content,voteup_count,created,updated,upvoted_followees,voting,review_info,is_labeled,label_info;data[*].author.badge[?(type=best_answerer)].topics',
                'offset':str(offset),
                'limit':'20',
                'sort_by':'voteups'
            }

            headers = {

                'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
                        }

            res = requests.get(url,headers=headers,params=params)

            res_json = res.json()


            data = res_json['data']

            for i in data:

                list = [i['title'],i['url'],i['excerpt']]

                articles_list.append(list)

            offset = offset + 20

            if offset > 40:
                break

        return articles_list


    def saveData(self):

        list = self.req()

        wb = openpyxl.Workbook()

        sheet = wb.active

        sheet.title = 'articles'

        sheet['A1'] = '文章标题'

        sheet['B1'] = '文章链接'

        sheet['C1'] = '文章内容'

        for data in list:

            sheet.append(data)

        wb.save('知乎文章.xlsx')



a = getZhihu()
a.saveData()